package handler

import (
	"homework-hub/model"
	"strconv"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	user := model.User{
		Username: username,
		Password: password,
	}
	err := model.DB.Create(&user).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Delete(c *gin.Context) {
	id := c.PostForm("id")

	var user model.User
	err := model.DB.Where("id=?", id).Delete(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var user []*model.User
	model.DB.Offset(offset).Limit(size).Find(&user)

	var total int64
	model.DB.Model(&user).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表获取成功",
		"user":  user,
		"total": total,
	})
	return
}
